﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;

namespace KPIS.GERP.GIMS.APP.APP_UI.Form
{
    public partial class ICM_Master_Purchase_Mapping : System.Web.UI.Page
    {
        Common.Main cn = new Common.Main();
        CommandControl cmdFac = new CommandControl();
        IBLLMasterPurchaseMapping bll = new MasterPurchaseMappingBLL();
        IBLLMasterPurchaseRule bllRule = new MasterPurchaseRuleBLL();
        IBLLTree bllTree = new TreeBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadDataGridRule();
                LoadPurchaseMethod();
                panelCommand.Visible = false;
                panelData.Visible = false;
            }
        }

        public void LoadDataGridRule()
        {
            IList<MasterPurchaseRuleInfo> info = bllRule.GetMasterPurchaseRule();
            GridRule.DataSource = info;
            GridRule.DataBind();
        }

        public void LoadDataGrid(int rule_seq)
        {
            IList<MasterPurchaseMappingInfo> info = bll.GetMasterPurchaseMappingWithRule(rule_seq);
            Grid.DataSource = info;
            GridGroupByExpression ge = new GridGroupByExpression(Grid.Columns[1]);
            Grid.MasterTableView.GroupByExpressions.Add(ge);
            Grid.DataBind();
            cmdFac.GridCommand(panelList, panelGrid, panelCommand);
        }

        public void LoadPurchaseMethod()
        {
            IList<TreeInfo> info = bllTree.GetPurchaseMethodTree();

            RadTreeView tree = (RadTreeView)cbMethod.Items[0].FindControl("TreeViewMethod");

            tree.DataSource = info;
            tree.DataBind();
        }

        public void GetKeyValue(string seq)
        {
            if (seq.Length > 0)
            {
                MasterPurchaseMappingInfo info = bll.GetMasterPurchaseMapping(Convert.ToInt32(seq));
                RadTreeView tree = (RadTreeView)cbMethod.Items[0].FindControl("TreeViewMethod");
                RadTreeNode node = new RadTreeNode();

                node = tree.FindNodeByValue(info.InfoMethod.InfoType.Seq.ToString() + "-" + info.InfoMethod.Seq.ToString());
                node.Selected = true;

                if (tree.SelectedNode != null)
                {
                    cbMethod.Text = tree.SelectedNode.Text;
                }
                else
                {
                    cbMethod.Text = "";
                }

                txtDescr.Text = info.Descr;
                //hdMinAmount.Value = info.Min_amount.ToString();
                //hdMaxAmount.Value = info.Max_amount.ToString();
                txtLessMinAmount.Text = info.Min_amount.ToString();
                txtBetweenMinAmount.Text = info.Min_amount.ToString();
                txtBetweenMaxAmount.Text = info.Max_amount.ToString();
                txtMoreMaxAmount.Text = info.Max_amount.ToString();
                lblAmountShow.Text = info.Amount_show;
                rdbAmountNone.Checked = false;
                rdbAmountLess.Checked = false;
                rdbAmountBetween.Checked = false;
                rdbAmountMore.Checked = false;

                if (info.Amount_type == "")
                {
                    rdbAmountNone.Checked = true;
                    rdbAmountNone_CheckedChanged(null, null);
                }
                else if (info.Amount_type == "<")
                {
                    rdbAmountLess.Checked = true;
                    rdbAmountLess_CheckedChanged(null, null);
                }
                else if (info.Amount_type == "-")
                {
                    rdbAmountBetween.Checked = true;
                    rdbAmountBetween_CheckedChanged(null, null);
                }
                else if (info.Amount_type == ">")
                {
                    rdbAmountMore.Checked = true;
                    rdbAmountMore_CheckedChanged(null, null);
                }

                cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
                cmdFac.SetPanelList(panelAmount, "View");
                cmdFac.SetViewMode(panelAmount);
                lblMethod.Text = cbMethod.Text;
            }
        }

        protected void AddNew_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList, panelGrid, panelCommand);
            rdbAmountNone_CheckedChanged(sender, e);
        }

        protected void Edit_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList, panelGrid, panelCommand);
            cmdFac.SetPanelList(panelAmount, "Edit");
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            IList<MasterPurchaseMappingInfo> infoList = new List<MasterPurchaseMappingInfo>();
            if (panelGrid.Visible)
            {
                foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
                {
                    MasterPurchaseMappingInfo info = new MasterPurchaseMappingInfo();
                    RecordInfo infoRecord = new RecordInfo();
                    info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                    infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                    infoRecord.Updated_when = DateTime.Now;
                    info.InfoRecord = infoRecord;
                    infoList.Add(info);
                }
            }
            else
            {
                MasterPurchaseMappingInfo info = new MasterPurchaseMappingInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(hdSeq.Value);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bll.DeleteAll(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadDataGrid(Convert.ToInt32(hdRule.Value));
        }

        protected void AddNewSave_Click(object sender, EventArgs e)
        {
            MasterPurchaseMappingInfo info = new MasterPurchaseMappingInfo();
            MasterPurchaseMethodInfo infoMethod = new MasterPurchaseMethodInfo();
            MasterPurchaseRuleInfo infoRule = new MasterPurchaseRuleInfo();
            RecordInfo infoRecord = new RecordInfo();
            RadTreeView tree = (RadTreeView)cbMethod.Items[0].FindControl("TreeViewMethod");
            if (tree.SelectedNode != null)
            {
                string[] all_value = tree.SelectedNode.Value.Split(new string[] { "-" }, StringSplitOptions.None);
                infoMethod.Seq = Convert.ToInt32(all_value[1]);
            } 

            infoRule.Seq = Convert.ToInt32(hdRule.Value);
            info.Descr = txtDescr.Text;
            if (rdbAmountNone.Checked)
            {
                info.Amount_type = "";
            }
            else if (rdbAmountLess.Checked)
            {
                info.Amount_type = "<";
                info.Min_amount = (txtLessMinAmount.Text.Length == 0 ? null : (Nullable<double>)Convert.ToDouble(txtLessMinAmount.Text));
            }
            else if (rdbAmountBetween.Checked)
            {
                info.Amount_type = "-";
                info.Min_amount = (txtBetweenMinAmount.Text.Length == 0 ? null : (Nullable<double>)Convert.ToDouble(txtBetweenMinAmount.Text));
                info.Max_amount = (txtBetweenMaxAmount.Text.Length == 0 ? null : (Nullable<double>)Convert.ToDouble(txtBetweenMaxAmount.Text));
            }
            else if (rdbAmountMore.Checked)
            {
                info.Amount_type = ">";
                info.Max_amount = (txtMoreMaxAmount.Text.Length == 0 ? null : (Nullable<double>)Convert.ToDouble(txtMoreMaxAmount.Text));
            }
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;

            info.InfoRule = infoRule;
            info.InfoMethod = infoMethod;
            info.InfoRecord = infoRecord;

            try
            {
                bll.CheckData(info);
            }
            catch (Exception ex)
            {
                RadManager1.Alert(ex.Message);
                return;
            }

            if (ValcbMethod.IsValid == false)
            {
                return;
            }

            try
            {
                bll.Insert(info);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
            LoadDataGrid(Convert.ToInt32(hdRule.Value));
        }

        protected void EditSave_Click(object sender, EventArgs e)
        {
            MasterPurchaseMappingInfo info = new MasterPurchaseMappingInfo();
            MasterPurchaseMethodInfo infoMethod = new MasterPurchaseMethodInfo();
            MasterPurchaseRuleInfo infoRule = new MasterPurchaseRuleInfo();
            RecordInfo infoRecord = new RecordInfo();
            RadTreeView tree = (RadTreeView)cbMethod.Items[0].FindControl("TreeViewMethod");

            info.Seq = Convert.ToInt32(hdSeq.Value);
            if (tree.SelectedNode != null)
            {
                string[] all_value = tree.SelectedNode.Value.Split(new string[] { "-" }, StringSplitOptions.None);
                infoMethod.Seq = Convert.ToInt32(all_value[1]);
            }

            infoRule.Seq = Convert.ToInt32(hdRule.Value);
            info.Descr = txtDescr.Text;
            if (rdbAmountNone.Checked)
            {
                info.Amount_type = "";
            }
            else if (rdbAmountLess.Checked)
            {
                info.Amount_type = "<";
                info.Min_amount = (txtLessMinAmount.Text.Length == 0 ? null : (Nullable<double>)Convert.ToDouble(txtLessMinAmount.Text));
            }
            else if (rdbAmountBetween.Checked)
            {
                info.Amount_type = "-";
                info.Min_amount = (txtBetweenMinAmount.Text.Length == 0 ? null : (Nullable<double>)Convert.ToDouble(txtBetweenMinAmount.Text));
                info.Max_amount = (txtBetweenMaxAmount.Text.Length == 0 ? null : (Nullable<double>)Convert.ToDouble(txtBetweenMaxAmount.Text));
            }
            else if (rdbAmountMore.Checked)
            {
                info.Amount_type = ">";
                info.Max_amount = (txtMoreMaxAmount.Text.Length == 0 ? null : (Nullable<double>)Convert.ToDouble(txtMoreMaxAmount.Text));
            }

            infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
            infoRecord.Updated_when = DateTime.Now;

            info.InfoRule = infoRule;
            info.InfoMethod = infoMethod;
            info.InfoRecord = infoRecord;

            if (ValcbMethod.IsValid == false)
            {
                return;
            }

            try
            {
                bll.CheckData(info);
            }
            catch (Exception ex)
            {
                RadManager1.Alert(ex.Message);
                return;
            }

            try
            {
                bll.Update(info);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
            GetKeyValue(hdSeq.Value);
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            cmdFac.CancelCommand(panelList, panelGrid, panelCommand);
            cmdFac.SetPanelList(panelAmount, "Cancel");
        }

        protected void ShowGrid_Click(object sender, EventArgs e)
        {
            LoadDataGrid(Convert.ToInt32(hdRule.Value));
        }

        protected void Grid_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadDataGrid(Convert.ToInt32(hdRule.Value));
        }

        protected void RadManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument == "Rule")
            {
                LoadDataGrid(Convert.ToInt32(hdRule.Value));
                MasterPurchaseRuleInfo info = bllRule.GetMasterPurchaseRule(Convert.ToInt32(hdRule.Value));
                SetHeader(info.Name);
                panelBlank.Visible = false;
                panelCommand.Visible = true;
                panelData.Visible = true;
            }
            else
            {
                GetKeyValue(e.Argument);
            }
        }

        protected void rdbAmountNone_CheckedChanged(object sender, EventArgs e)
        {
            DisableRadNumericTextBox(txtLessMinAmount);
            DisableRadNumericTextBox(txtBetweenMinAmount);
            DisableRadNumericTextBox(txtBetweenMaxAmount);
            DisableRadNumericTextBox(txtMoreMaxAmount);
        }

        protected void rdbAmountLess_CheckedChanged(object sender, EventArgs e)
        {
            EnableRadNumericTextBox(txtLessMinAmount);
            DisableRadNumericTextBox(txtBetweenMinAmount);
            DisableRadNumericTextBox(txtBetweenMaxAmount);
            DisableRadNumericTextBox(txtMoreMaxAmount);
            txtLessMinAmount.Focus();
        }

        protected void rdbAmountBetween_CheckedChanged(object sender, EventArgs e)
        {
            DisableRadNumericTextBox(txtLessMinAmount);
            EnableRadNumericTextBox(txtBetweenMinAmount);
            EnableRadNumericTextBox(txtBetweenMaxAmount);
            DisableRadNumericTextBox(txtMoreMaxAmount);
            txtBetweenMinAmount.Focus();
        }

        protected void rdbAmountMore_CheckedChanged(object sender, EventArgs e)
        {
            DisableRadNumericTextBox(txtLessMinAmount);
            DisableRadNumericTextBox(txtBetweenMinAmount);
            DisableRadNumericTextBox(txtBetweenMaxAmount);
            EnableRadNumericTextBox(txtMoreMaxAmount);
            txtMoreMaxAmount.Focus();
        }

        private void DisableRadNumericTextBox(RadNumericTextBox txt)
        {
            txt.Text = "";
            txt.Enabled = false;
        }

        private void EnableRadNumericTextBox(RadNumericTextBox txt)
        {
            txt.Enabled = true;
        }

        private void SetHeader(string header)
        {
            lblHeaderList.Text = "วิธีการจัดหาตาม [" + header + "]";
        }

        protected void OnAjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            RadAjaxPanel1.Controls.Add(Page.LoadControl("../UserControl/Personal_Data.ascx"));
        }

        protected void clearFilter_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid.MasterTableView.FilterExpression = string.Empty;
            LoadDataGrid(Convert.ToInt32(hdRule.Value));
        }
    }
}
